<template>
  <div>
    <Card :bordered="false" dis-hover class="">
      <Form
        ref="orderData"
        :model="orderData"
        :label-width="labelWidth"
        :label-position="labelPosition"
        class="tabform"
        @submit.native.prevent
        label-width="120"
      >
        <div class="acea-row">
          <FormItem :label="$t('page.order.date')+'：'">
            <DatePicker
                    :editable="false"
                    :clearable="true"
                    @on-change="onchangeTime"
                    :value="timeVal"
                    format="yyyy/MM/dd HH:mm:ss"
                    type="datetimerange"
                    placement="bottom-start"
                    placeholder=""
                    style="width: 250px"
                    class="mr30"
                    :options="options"
            ></DatePicker>
          </FormItem>
          <FormItem :label="$t('page.order.search')+'：'">
            <Input
                    v-model="orderData.real_name"
                    placeholder=""
                    element-id="name"
                    clearable
                    style="width:250px;"
                    maxlength="20"
            >
              <Select
                      v-model="orderData.field_key"
                      slot="prepend"
                      style="width:80px;"
                      default-label="all"
              >
                <Option value="all">{{ $t('page.order.all') }}</Option>
                <Option value="order_id">{{ $t('page.order.order_no') }}</Option>
                <Option value="location">{{ $t('page.order.location') }}</Option>
                <Option value="customer">{{ $t('page.order.customer') }}</Option>
                <Option value="po_number">{{ $t('page.order.po_no') }}</Option>
              </Select>
            </Input>
          </FormItem>
          <FormItem :label="$t('page.order.order')+ $t('page.order.type')+'：'">
            <Select
                v-model="orderData.order_type"
                style="width:120px;"
                placeholder=""
            >
              <Option value="unfulfilled">{{ $t('page.order.unfulfilled') }}</Option>
              <Option value="unpaid">{{ $t('page.order.unpaid') }}</Option>
              <Option value="paid">{{ $t('page.order.paid') }}</Option>
            </Select>
          </FormItem>
          <Button type="primary" @click="userSearchs" class="ml20">{{ $t('page.order.search') }}</Button>
          <Button @click="reset" class="ml20">{{ $t('page.order.reset') }}</Button>
        </div>
      </Form>
    </Card>

    <Card :bordered="false" dis-hover class="mt25" style="background: #F5F7F9;">
      <Row :gutter="16" style="justify-content: space-between;">
        <Col span="6" v-for="(val, i) in allHeaderListType" :key="i" style="background-color: white;display: flex; justify-content: space-evenly;padding: 8px;
        border-radius: 1.2rem;">
          <div style="padding-top: 1rem 0;">
            <p class="titleItem">{{ val.name }}</p>
            <p class="countItem">{{val.count}}</p>
            <p class="todayItem">今日新增: {{val.today}}</p>
<!--            <CountUp :end="val.count" :duration="3" :ref="'HeaderList'+i" v-font="24" />-->
          </div>
          <div class="PicItem">
            <img style="width: 100%; height: 100%;object-fit: contain" :src="val.pic" alt="">
          </div>
        </Col>
      </Row>
    </Card>


    <Card :bordered="true" dis-hover class="mt20">
      <div class="product_tabs tabbox">
        <Tabs v-model="orderData.type" @on-click="onClickTab">
          <TabPane v-for="(item, index) in headerListType" :key="index" :label="item.name + '(' + item.count + ')'"
                   :name="item.type.toString()" />
        </Tabs>
      </div>
      <div class="table mt20">
        <!-- 自建订单-->
        <div>
          <router-link :to="roterPre+'/order/edit'">
            <Button type="primary" class="bnt">{{ $t('page.order.create') }} {{ $t('page.order.order') }}</Button>
          </router-link>
        </div>
        <div>
          <vxe-table
              border="inner"
              ref="xTable"
              class="mt20"
              :loading="loading"
              row-id="id"
              :expand-config="{accordion: true}"
              :checkbox-config="{reserve: true}"
              @checkbox-change="checkboxItem"
              :data="thisOrderList">
            <vxe-column field="order_no" :title="$t('page.order.order_no')" min-width="190"></vxe-column>
            <vxe-column field="created_at" :title="$t('page.order.date')" min-width="190">
              <template v-slot="{ row }">
                <span>{{ formatTimeNative(row.created_at) }}</span> <!-- 调用格式化方法 -->
              </template>
            </vxe-column>
            <vxe-column field="store_customer" :title="$t('page.order.customer')" min-width="190">
              <template v-slot="{ row }">
                <div slot="content">
                  <div>
                    <p>{{ row.store_customer.name }}</p>
                    <p> {{row.store_customer.email}}</p>
                  </div>
                </div>
              </template>
            </vxe-column>
<!--            <vxe-column field="sku" title="Product" min-width="220">-->
<!--              <template v-slot="{ row }">-->
<!--                <div slot="content" v-for="(item, index) in row.store_order_items ">-->
<!--                  <div>-->
<!--                    <p>{{ item.product_name }}</p>-->
<!--                    <p> {{item.sku}}</p>-->
<!--                    <p class="tabBox_pice">{{ "$" + item.pay_price + " x " + item.quantity }}</p>-->
<!--                  </div>-->
<!--                </div>-->
<!--              </template>-->
<!--            </vxe-column>-->
            <vxe-column field="pay_amount" :title="$t('page.order.order')+' '+$t('page.order.total')" min-width="120">
              <template v-slot="{ row }">
                <Numeral :value="row.pay_amount" format="0,0.00">
                  <template #prefix>
                    <strong>$</strong>
                  </template>
                </Numeral>
              </template>
            </vxe-column>
            <vxe-column field="pay_type" :title="$t('page.order.payment')+' ' +$t('page.order.terms')" min-width="120">
              <template v-slot="{ row }">
                <spam v-if="row.pay_type == 'before_mention'">{{$t('page.order.due_on_receipt')}}</spam>
                <spam v-else-if="row.pay_type == 'central_mention'">{{  $t('page.order.due_on_fulfillment') }}</spam>
              </template>
            </vxe-column>
            <vxe-column field="pay_status" :title="$t('page.order.payment')+' '+$t('page.order.status')" min-width="120">
              <template v-slot="{ row }">
                <Tag color="gold" v-if="row.pay_status == 0">{{ $t('page.order.unpaid') }}</Tag>
                <Tag color="green" v-if="row.pay_status == 1">{{ $t('page.order.paid') }}</Tag>
              </template>
            </vxe-column>

            <vxe-column field="fulfilled_status" :title="$t('page.order.fulfillment')+' '+$t('page.order.status')" min-width="150">
              <template v-slot="{ row }">
                <Tag color="gold" v-if="row.fulfilled_status == 1">{{ $t('page.order.fulfilled') }}</Tag>
                <Tag color="green" v-if="row.fulfilled_status == 0">{{ $t('page.order.unfulfilled') }}</Tag>
              </template>
            </vxe-column>

<!--            <vxe-column field="" :title="$t('page.order.location')" min-width="120">-->
<!--              <template v-slot="{ row }">-->
<!--                <p>CA 5005</p>-->
<!--              </template>-->
<!--            </vxe-column>-->

            <vxe-column field="" :title="$t('page.order.ob')" min-width="120">
              <template v-slot="{ row }">
                <span v-if="row.pay_type == 'central_mention'" v-for="(item, i) in row.store_order_ob_no" :key="i">{{ item.ob_no }} <br></span>
                <span v-if="row.pay_type == 'before_mention' && row.pay_status == 1" v-for="(item, i) in row.store_order_ob_no" :key="i">{{ item.ob_no }} <br></span>
              </template>
            </vxe-column>

            <vxe-column field="po_number" :title="$t('page.order.po_no')" min-width="120"></vxe-column>

            <vxe-column field="order_status" :title="$t('page.order.listing_status')" min-width="120">
              <template v-slot="{ row }">
                <p v-if="row.order_status == 0">{{$t('page.order.draft')}}</p>
                <p v-if="row.order_status == 1">{{$t('page.order.underReview')}}</p>
                <p v-if="row.order_status == 2">{{$t('page.order.pending')}}</p>
                <p v-if="row.order_status == 3">{{$t('page.order.cancel')}}</p>
                <p v-if="row.order_status == 4">{{$t('page.order.closed')}}</p>
              </template>
            </vxe-column>

            <vxe-column field="action" :title="$t('page.order.operate')" align="center" width="250" fixed="right">
              <template #default="{ row, rowIndex }">
                <a @click="getData(row.id,0)">{{$t('page.order.detail')}}</a>
                <Divider type="vertical" v-if="row.order_status == 0 ||  row.order_status == 1 ||  row.order_status == 2"/>
                <a @click="cancelOrder(row.id)" v-if="row.order_status == 0 ||  row.order_status == 1 ||  row.order_status == 2">{{$t('page.order.cancel')}}</a>
                <Divider type="vertical" v-if="row.order_status == 0 ||  row.order_status == 1"  />
                <a @click="edit(row)" v-if="row.order_status == 0 ||  row.order_status == 1">{{$t('page.order.edit')}}</a>
                <Divider type="vertical" v-if="row.order_status == 0" />
                <a @click="submitOrder(row.id)" v-if="row.order_status == 0">{{$t('page.order.save')}}</a>
                <Divider type="vertical" v-if="row.order_status == 1" />
                <a @click="reviewOrder(row.id)" v-if="row.order_status == 1">{{$t('page.order.submit')}}</a>
              </template>
            </vxe-column>
          </vxe-table>
          <div class="acea-row row-right mt15">
            <Page :total="thisOrderTotal" :current="orderData.page"  @on-change="pageChange"
                  :page-size="orderData.limit"/>
          </div>
        </div>
      </div>

    </Card>
    <!-- 详情 -->
    <details-from
      ref="detailss"
      :orderDatalist="orderDatalist"
      :orderId="orderId"
      :row-active="rowActive"
      :formType="1"
    ></details-from>
    <!-- 会员详情-->
    <user-details ref="userDetails" fromType="order"></user-details>
    <!-- 备注 -->
    <order-remark
      ref="remarks"
      :orderId="orderId"
      @submitFail="submitFail"
    ></order-remark>
    <!-- 记录 -->
    <order-record ref="record"></order-record>

    <auto-send
        ref="sends"
        :selectArr="checkUidList"
		:isAll="isAll"
    ></auto-send>
    <queue-list ref="queue"></queue-list>
  </div>
</template>

<script>
import { mapState } from "vuex";
import editFrom from "@/components/from/from";
import orderSend from "./components/orderSend";
import detailsFrom from "./components/orderDetails";
import orderRecord from "./components/orderRecord";
import orderRemark from "./components/orderRemark";
import userDetails from "@/components/userDetails/userDetails";
import autoSend from "./components/autoSend";
import timeOptions from "@/utils/timeOptions";
import Setting from "@/setting";
import exportExcel from "@/utils/newToExcel.js";
import {
  orderList, shopifyOrderList, orderHeaderInfo, orderAllHeaderInfo, orderInfoApi
} from "@/api/order";
import details from "@/components/details/index.vue";
import orderPic1 from '@/assets/images/orderNumber.png'
import orderPic2 from '@/assets/images/monery.png'
import orderPic3 from '@/assets/images/car.png'
import orderPic4 from '@/assets/images/alertPay.png'
export default {
  name: "index",
  components: {
    editFrom,
    detailsFrom,
    orderRecord,
    orderRemark,
    orderSend,
    userDetails,
    autoSend,
  },
  data() {
    const codeNum = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请填写核销码"));
      }
      // 模拟异步验证效果
      if (!Number.isInteger(value)) {
        callback(new Error("请填写12位数字"));
      } else {
        const reg = /\b\d{12}\b/;
        if (!reg.test(value)) {
          callback(new Error("请填写12位数字"));
        } else {
          callback();
        }
      }
    };
    return {
      roterPre:Setting.roterPre,
      isAll: 0,
      isCheckBox: false,
      checkUidList:[],
      manualModal:false,
      timeVal: [],
      allHeaderList: [],
      // 订单列表
      orderData: {
        page: 1,
        limit: 10,
        type: "2",
        order_type: "",
        status: "",
        data: "",
        real_name: "",
        pay_type: "",
        field_key: "all"
      },
      total: 0,
      thisOrderList: [],
      thisOrderTotal: 0,
      loading: false,
      orderConNum:0,
      orderConId:0,
      orderId: 0,
      delfromData: {},
      rowActive: {},
      orderDatalist: null,
      FromData: null,
      file: "",
      uploadAction: `${Setting.apiBaseURL}/file/upload/1`,
      uploadHeaders: {},
      fileList: [],
      headerList:[],
      modals2: false,
      writeOffRules: {
        code: [{ validator: codeNum, trigger: "blur", required: true }],
      },
      writeOffFrom: {
        code: "",
        confirm: 0,
      },
      exportListOn: 0,
      exportList: [
        {
          name: "1",
          label: "导出发货单",
        },
        {
          name: "0",
          label: "导出订单",
        },
      ],
    };
  },
  watch: {
    $route() {
      if (this.$route.fullPath === `${Setting.roterPre}/order/list?type=7&status=1`) {
        this.getPath();
      }
    }
  },
  computed: {
    options(){
      return  timeOptions;
    },
    details() {
      return details
    },
    allHeaderListType(){
      var Orders,Items,Fulfilled,Paid = 0
      for (let i = 0; i < this.allHeaderList.length; i++) {
        if (this.allHeaderList[i].type == 1) {
          Items = this.allHeaderList[i].count
        }else if (this.allHeaderList[i].type == 2) {
          Fulfilled = this.allHeaderList[i].count
        }else if (this.allHeaderList[i].type == 3) {
          Paid = this.allHeaderList[i].count
        }else if (this.allHeaderList[i].type == 0) {
          Orders = this.allHeaderList[i].count
        }
      }
      return [
        {type: 0, name:  $t('page.order.orders'), count: Orders, pic:orderPic1},
        {type: 1, name: $t('page.order.items'), count: Items, pic:orderPic2},
        {type: 2, name: $t('page.order.orders_fulfilled'), count: Fulfilled, pic:orderPic3},
        {type: 3, name: $t('page.order.paid_orders'), count: Paid, pic:orderPic4}
      ]
    },
    headerListType(){
      var pending,underReview,completed,draft,cancel = 0
      for (let i = 0; i < this.headerList.length; i++) {
        if (this.headerList[i].type == 1) {
          underReview = this.headerList[i].count
        }else if (this.headerList[i].type == 2) {
          pending = this.headerList[i].count
        }else if (this.headerList[i].type == 3) {
          cancel = this.headerList[i].count
        }else if (this.headerList[i].type == 4) {
          completed = this.headerList[i].count
        }else if (this.headerList[i].type == 0) {
          draft = this.headerList[i].count
        }
      }
	  
      return [
        {type: 2, name: $t('page.order.pending'), count: pending},
        {type: 1, name: $t('page.order.underReview'), count: underReview},
        {type: 4, name: $t('page.order.closed'), count: completed},
        {type: 0, name: $t('page.order.draft'), count: draft},
        {type: 3, name: $t('page.order.cancel'), count: cancel}
      ]
    },
    ...mapState("store/layout", ["isMobile"]),
    labelWidth() {
      return this.isMobile ? 0 : 80;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    },
  },
  created() {
    this.getHeader();
    this.getAllHeader();
    if (this.$route.fullPath === `${Setting.roterPre}/order/list?type=7&status=1`) {
      this.getPath();
    }
  },
  mounted() {

  },
  methods: {
    formatTimeNative(timestamp) {
      const date = new Date(timestamp);
      const now = new Date();
      const isToday =
          date.getDate() === now.getDate() &&
          date.getMonth() === now.getMonth() &&
          date.getFullYear() === now.getFullYear();

      // 时间格式（小时:分钟 + am/pm）
      const timeOptions = {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      };
      const timeString = new Intl.DateTimeFormat('en-US', timeOptions).format(date);

      return isToday ? `Today at ${timeString}` : new Intl.DateTimeFormat('en-US', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      }).format(date);
    },
    //切换头部列表
    onClickTab(e) {
      this.orderData.type = e;
      this.orderData.page = 1;
      this.getHeader();
    },
    //订单详情
    orderDetail(row) {

    },
    //头部列表
    getHeader() {
      this.loading = true;
      orderHeaderInfo(this.orderData).then((res) => {
        this.headerList = res.data.list;
        this.getThisOrderList();
      });
    },
    //头部统计
    getAllHeader() {
      this.loading = true;
      orderAllHeaderInfo(this.orderData).then((res) => {
        this.allHeaderList = res.data.list;
      });
    },

    //跳转刷新
    getPath() {
      this.orderData.page = 1;
      this.orderData.status = this.$route.query.status;
      this.getHeader();
    },
	allReset(){
	  this.isAll = 0;
	  this.isCheckBox = false;
	  this.$refs.xTable.setAllCheckboxRow(false);
	  this.checkUidList = [];
	},
	checkboxItem(e){
	  let id = parseInt(e.rowid);
	  let index = this.checkUidList.indexOf(id);
	  if(index !== -1){
	    this.checkUidList = this.checkUidList.filter((item)=> item !== id);
	  }else{
	    this.checkUidList.push(id);
	  }
	},

    reset(){
      this.timeVal = [];
      this.orderData = {
        page: 1,
        limit: 10,
        type: "",
        status: "",
        data: "",
        real_name: "",
        pay_type: ""
      };
      this.getHeader();
    },

    // 订单导出
    async exports(value) {
      this.exportListOn = this.exportList.findIndex(
              (item) => item.name === value
      );
      let [th, filekey, data, fileName] = [[], [], [], ""];
      let excelData = JSON.parse(JSON.stringify(this.orderData));
      excelData.page = 1;
      excelData.type = value;
      excelData.ids = this.checkUidList.join();
      for (let i = 0; i < excelData.page + 1; i++) {
        let lebData = await this.downOrderData(excelData);
        if (!fileName) fileName = lebData.filename;
        if (!filekey.length) {
          filekey = lebData.filekey;
        }
        if (!th.length) th = lebData.header;
        if (lebData.export.length) {
          data = data.concat(lebData.export);
          excelData.page++;
        } else {
          exportExcel(th, filekey, fileName, data);
          return;
        }
      }
    },
    downOrderData(excelData) {
      return new Promise((resolve, reject) => {
        storeOrderApi(excelData).then((res) => {
          return resolve(res.data);
        });
      });
    },

    // 下载物流公司对照表
    async getExpressList() {
      let [th, filekey, data, fileName] = [[], [], [], ""];
      let lebData = await this.getExcelData();
      if (!fileName) fileName = lebData.filename;
      if (!filekey.length) {
        filekey = lebData.filekey;
      }
      if (!th.length) th = lebData.header;
      data = lebData.export;
      exportExcel(th, filekey, fileName, data);
    },
    getExcelData() {
      return new Promise((resolve, reject) => {
        exportExpressList().then((res) => {
          return resolve(res.data);
        });
      });
    },


    //提交订单
    submitOrder(id){
      this.delfromData = {
        title: "提交订单",
        info: "您确认提交此订单吗?",
        url: `/order/set_show/${id}/1`,
        method: "put",
        ids: "",
      };
      this.$modalSure(this.delfromData)
          .then((res) => {
            this.$Message.success(res.msg);
            this.getHeader();
          })
          .catch((res) => {
            this.$Message.error(res.msg);
          });
    },
    //确认订单
    reviewOrder(id){
      this.delfromData = {
        title: "确认订单",
        info: "你确定要提交订单吗？提交后将占用对应商品库存，库存锁定后不可手动释放，请确认后操作～",
        url: `/order/set_show/${id}/2`,
        method: "put",
        ids: "",
      };
      this.$modalSure(this.delfromData)
          .then((res) => {
            this.$Message.success(res.msg);
            this.getHeader();
          })
          .catch((res) => {
            this.$Message.error(res.msg);
          });
    },

    cancelOrder(id){
      this.delfromData = {
        title: "取消订单",
        info: "您是否确认要取消该订单？取消后，订单相关的商品库存将释放.",
        url: `/order/set_show/${id}/3`,
        method: "put",
        ids: "",
      };
      this.$modalSure(this.delfromData)
          .then((res) => {
            this.$Message.success(res.msg);
            this.getHeader();
          })
          .catch((res) => {
            console.log("err:",res)
            this.$Message.error(res.msg);
          });
    },
    // 编辑
    edit(row) {

      this.$router.push({ path: Setting.roterPre+"/order/edit/" + row.id });
    },
    // 修改成功
    submitFail() {
      this.getHeader();
      if(this.orderConNum !=1){
        this.getData(this.orderId,1);
      }else{
        this.$refs.detailss.getSplitOrder(this.orderConId);
      }
    },
    // 获取详情表单数据
    getData(id,type) {
      orderInfoApi(id).then(async (res) => {
        if(!type){
          this.$refs.detailss.modals = true;
        }
        this.$refs.detailss.activeName = 'detail';
        this.orderDatalist = res.data.info;
      }).catch((res) => {
        this.$Message.error(res.msg);
      });
    },

    // 删除单条订单
    delOrder(row, data) {
      if (row.is_del === 1) {
        this.$modalSure(data)
                .then((res) => {
                  this.$Message.success(res.msg);
                  this.getHeader();
                  this.$refs.detailss.modals = false;
                })
                .catch((res) => {
                  this.$Message.error(res.msg);
                });
      } else {
        const title = "错误！";
        const content =
                "<p>您选择的的订单存在用户未删除的订单，无法删除用户未删除的订单！</p>";
        this.$Modal.error({
          title: title,
          content: content,
        });
      }
    },
    getThisOrderList(){
      this.loading = true;
      orderList(this.orderData).then(res=>{
        let data = res.data;
        this.$set(this,'thisOrderList',data.list);
        this.thisOrderTotal = res.data.count;
        this.loading = false;
      }).catch(err=>{
        this.loading = false;
        this.$Message.error(err.msg)
      })
    },
    // 具体日期
    onchangeTime(e) {
      if (e[1].slice(-8) === "00:00:00") {
        e[1] = e[1].slice(0, -8) + "23:59:59";
        this.timeVal = e;
      } else {
        this.timeVal = e;
      }
      this.orderData.data = this.timeVal[0] ? this.timeVal.join("-") : "";
      this.orderData.page = 1;
	    this.allReset();
      this.getHeader();
    },
    pageChange(index) {
      this.orderData.page = index;
      this.getHeader();
    },
    userSearchs(){
        this.allReset();
        this.orderData.page = 1;
        this.getHeader();
    }
  },
};
</script>

<style lang="stylus" scoped>
  .ivu-col-span-6{
    flex: 0 0 24.5% !important;
  }
  .PicItem{
    height 10rem;
    width: 10rem;
    margin: 0.5rem 0;
  }
  .titleItem{
    font-size: 1.6rem;
    font-weight: bold;
    color: black;
  }
  .countItem{
    font-size: 3rem;
    font-weight: bold;
    color: #630F81;
  }
  .todayItem{
    font-size: 1.1rem;
    font-weight: bold;
    color: #B167CA;
  }

  .tdinfo{
    margin-left: 75px;
    margin-top: 16px;
  }
  .expand-row{
    margin-bottom: 16px;
    font-size: 12px;
  }
  .tabBox {
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;

    .tabBox_img {
      width: 30px;
      height: 30px;

      img {
        width: 100%;
        height: 100%;
      }
    }

    .tabBox_tit {
      width:267px;
      height:30px;
      line-height:30px;
      font-size: 12px !important;
      margin: 0 2px 0 10px;
      letter-spacing: 1px;
      box-sizing: border-box;
    }
  }
  .tabBox +.tabBox{
    margin-top:5px;
  }
</style>
